import json
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from accounts_sys.models import User
from utils.response_utils import method_disallowed_response, login_status_response, build_response, \
    permission_denied_response
from utils.session_utils import has_login, get_login_id

from utils.string_utils import *
from utils.type_utils import *

from portal_sys.models import Claim
from django.conf import settings

from elastic_sys.elastic.elastic_manager import get_entity
from elastic_sys.elastic.entity_definer import get_entity_enum_by_type_name, EntityEnum


@csrf_exempt
def get_review_list(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')

    if not has_login(request):
        return login_status_response()

    user = User.objects.get(id=get_login_id(request))
    if user.user_type not in ['admin']:
        return permission_denied_response(user.user_type, 'admin')

    claims = Claim.objects.filter(status="pending")
    claim_list = []
    for claim in claims:
        entity = get_entity(EntityEnum.scholar, str(claim.scholar_id), essential=True)
        claim_list.append({
            "id": claim.id,
            "claim_time": claim.claim_time,
            "user": claim.user_id.parse_dict(),
            "scholar": entity,
            "introduction": claim.introduction,
            "material": "http://" + request.get_host() + settings.MEDIA_URL + str(claim.scholar_id) + "/" +claim.material_path
        })

    return build_response(other_info={'claim': claim_list}, msg="获取门户申请记录成功")


@csrf_exempt
def review_approve(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    user = User.objects.get(id=get_login_id(request))
    if user.user_type not in ['admin']:
        return permission_denied_response(user.user_type, 'admin')

    data = json.loads(request.body)
    claim_id = data.get('claim_id')

    # ucliam = Claim.objects.get(user_id=user)
    # if ucliam and str(ucliam.id)!=claim_id :
    #     return build_response(errno=2002, msg="这个用户已认领门户")

    claim = Claim.objects.get(id=claim_id)
    if claim.status == "approve":
        return build_response(errno=2001, msg="学者门户已被认领")

    scholar = get_entity(EntityEnum.scholar, str(claim.scholar_id), essential=True)
    claimed_user = User.objects.get(id=claim.user_id.id)
    claimed_user.user_type = "scholar"
    claimed_user.introduction = claim.introduction
    claimed_user.scholar_id = claim.scholar_id
    claimed_user.scholar_name = scholar.get("display_name")
    claim.status = "approve"
    claimed_user.save()
    claim.save()

    return build_response(msg='门户申请已成功通过')


@csrf_exempt
def review_reject(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    user = User.objects.get(id=get_login_id(request))
    if user.user_type not in ['admin']:
        return permission_denied_response(user.user_type, 'admin')

    data = json.loads(request.body)
    claim_id = data.get('claim_id')

    claim = Claim.objects.get(id=claim_id)
    claim.status = "reject"
    claim.save()
    claimed_user = claim.user_id
    claimed_user.is_claiming = False
    claimed_user.save()

    return build_response(msg='门户申请已成功驳回')


@csrf_exempt
def admin_register(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    user = User.objects.get(id=get_login_id(request))
    if user.user_type not in ['admin']:
        return permission_denied_response(user.user_type, 'admin')

    data = json.loads(request.body)
    user_name = data.get('user_name')
    email = data.get('email')
    password = data.get('password')

    if contains_false_val(user_name, email, password):  # 为空串
        return build_response(errno=2001, msg="user_name, email, password均不能为空")

    if not (2 <= len(user_name) <= 31) or valid_email(user_name):  # 不可以使用邮箱格式的用户名
        return build_response(errno=2002, msg="用户名不合法")

    if not (6 <= len(email) <= 63) or not valid_email(email):
        return build_response(errno=2003, msg="邮箱不合法")

    if not (4 <= len(password) <= 31):
        return build_response(errno=2004, msg="密码不合法")

    if User.objects.filter(user_name=user_name).exists():
        return build_response(errno=2005, msg="用户名已存在")

    if User.objects.filter(email=email).exists():
        return build_response(errno=2006, msg="邮箱已存在")

    User.objects.create(user_name=user_name, email=email, password=password, user_type="admin")

    return build_response(msg='注册成功')
